package com.mercenary.wein.screenControl.ui;

import com.mercenary.wein.screenControl.bean.DeviceBean;
import com.mercenary.wein.screenControl.bean.GroupMetaBean;
import com.mercenary.wein.screenControl.dao.DeviceDao;
import com.mercenary.wein.screenControl.deviceControll.AndroidDevice;
import com.mercenary.wein.screenControl.service.GroupService;
import com.mercenary.wein.screenControl.ui.inter.ChoosedDeviceInter;
import com.mercenary.wein.screenControl.ui.inter.DeviceTableOb;
import com.mercenary.wein.screenControl.ui.inter.GroupComboBoxOb;
import com.mercenary.wein.screenControl.ui.util.CommonTools;

import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.*;
import java.util.List;

/**
 * Created by tuxiao on 2017/3/17.
 */
public class DeviceTable extends JScrollPane implements GroupComboBoxOb, ChoosedDeviceInter {
    final List<DeviceBean> deviceBeanList = new ArrayList<DeviceBean>();
    private DefaultTableModel tm;
    final static GroupService groupService = new GroupService();
    final static DeviceDao deviceDao = new DeviceDao();
    final MyJtable table;
    final JPopupMenu jPopupMenu = new JPopupMenu("设置分组");
    long currentGid = 0;
    boolean ifListen = true;//是否启用监听方法
    DeviceTableOb ob = null;

    public void registerObserver(DeviceTableOb ob){
        this.ob = ob;
    }

    public void notifyGroupChange(String serialNo){
        if(ob!=null){
            ob.refreshData(serialNo);
        }
    }

    public long getCurrentGid() {
        return currentGid;
    }

    public List<AndroidDevice> getChoosedADevices() {
        return choosedDcdMap;
    }

    //保存所有被选中的显示设备的Map
    public final List<AndroidDevice> choosedDcdMap = new ArrayList<AndroidDevice>();

    public List<DeviceBean> getChoosedDevices() {
        return deviceBeanList;
    }

    public DeviceTable() {
        super();
        Vector<String> columnNames = new Vector<String>();
        columnNames.add("手机");
        columnNames.add("分组");
        columnNames.add("设备号");
        columnNames.add("分组id");
        Vector<List<String>> deviceList = new Vector<List<String>>();
        tm = new DefaultTableModel(deviceList, columnNames);
        table = new MyJtable(tm);
        table.setRowSelectionAllowed(true);
        DefaultTableCellRenderer tableCellRenderer = new DefaultTableCellRenderer();// 设置table内容居中
        table.setDefaultRenderer(Object.class, tableCellRenderer);
        table.setPreferredScrollableViewportSize(new Dimension(100, 20));
        this.setViewportView(table);
        table.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getButton() == MouseEvent.BUTTON3 && ifListen) {
                    int row = table.getSelectedRow();
                    int column = table.getSelectedColumn();
//                    String group = tm.getValueAt(table.getSelectedRow(), table.getSelectedColumn()).toString();
                    final DeviceBean db = deviceBeanList.get(row);
                    if (column == 0) {//修改手机名称
                        String s = JOptionPane.showInputDialog(table, "现在名称是："+db.getDname(), "修改手机名称", JOptionPane.OK_CANCEL_OPTION);
                        if (s != null) deviceDao.setDeviceName(db.getSerialNo(), s);
                        if(MainFrame.dcdMap.containsKey(db.getSerialNo()))MainFrame.dcdMap.get(db.getSerialNo()).refreshData();
                    }else if(column == 1){//弹出右键列表选择
                        List<GroupMetaBean> groupMetaBeens = groupService.getAllGroupMetaBean();
                        int i = jPopupMenu.getComponentCount();//先要移除原有的项目
                        while(i>0){
                            jPopupMenu.remove(0);
                            i--;
                        }
                        for(final GroupMetaBean groupMetaBean:groupMetaBeens){
                            JMenuItem item = new JMenuItem(groupMetaBean.getGname());
                            item.addActionListener(new ActionListener() {
                                public void actionPerformed(ActionEvent e) {
                                    groupService.updateDeviceGroup(groupMetaBean.getGcode(),db.getSerialNo());
                                    refreshData(getCurrentGid());
                                    if(MainFrame.dcdMap.containsKey(db.getSerialNo()))MainFrame.dcdMap.get(db.getSerialNo()).refreshData();
                                }
                            });
                            jPopupMenu.add(item);
                        }
                        jPopupMenu.show(table,e.getX(),e.getY());
                    }
                    refreshData(0l);
                }else if(e.getClickCount()==2){
                    int row = table.getSelectedRow();
                    DeviceBean db = deviceBeanList.get(row);
                    notifyGroupChange(db.getSerialNo());
                }
            }


        });
    }

    public void refreshData(long gid) {
        currentGid=gid;
        initTM();
        List<DeviceBean> deviceBeens = groupService.getDevicesByGid(gid);
        for (DeviceBean db : deviceBeens) {
            insertData(db);
        }
        CommonTools.getAndroidDeviceByDeviceBean(MainFrame.dcdMap, deviceBeanList, choosedDcdMap);
        this.updateUI();
    }

    public void insertData(DeviceBean deviceBean) {
        deviceBeanList.add(deviceBean);
        tm.addRow(new String[]{deviceBean.getDname(), groupService.getGroupName(deviceBean.getGcode()), deviceBean.getSerialNo(), deviceBean.getGcode() + ""});
        tm.fireTableDataChanged();
    }

    public void deleteData(DeviceBean deviceBean) {
        for (int i = 0; i < tm.getRowCount(); i++) {
//            String tm.getValueAt()
        }
    }

    public void initTM() {
        while (tm.getRowCount() > 0) {
            tm.removeRow(0);
        }
        deviceBeanList.removeAll(deviceBeanList);
    }

    public void stopListen(){
        ifListen =false;
    }

}

class MyJtable extends JTable {
    public MyJtable(DefaultTableModel tm) {
        super(tm);
        TableColumnModel columnModel = getColumnModel();
        TableColumn column = columnModel.getColumn(2);
        column.setMinWidth(2);
        column.setMaxWidth(2);
        column = columnModel.getColumn(3);
        column.setMinWidth(3);
        column.setMaxWidth(3);
    }


    public boolean isCellEditable(int row, int column) {
        return false;
    }
}
